<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="node_modules/xterm/dist/xterm.css" />
    <script src="node_modules/xterm/dist/xterm.js"></script>
    <script src="node_modules/xterm/dist/addons/fit/fit.js"></script>
    <script src="node_modules/xterm/dist/addons/winptyCompat/winptyCompat.js"></script>
    <script src="node_modules/xterm/dist/addons/webLinks/webLinks.js"></script>
</head>
<body>
<form>
    namespace:<input type="text" id="podNs">
    podName:<input  type="text" id="podName">
    containerName:<input  type="text" id="containerName">
    <input id="ssh" type="button" value="ssh">
</form>
<div id="terminal"></div>
<script>
    // xterm配置自适应大小插件
    Terminal.applyAddon(fit);

    // 这俩插件不知道干嘛的, 用总比不用好
    Terminal.applyAddon(winptyCompat)
    Terminal.applyAddon(webLinks)

    // 新建终端
    function openTerminal() {
        // 创建终端
        var term = new Terminal();
        term.open(document.getElementById('terminal'));

        // 使用fit插件自适应terminal size
        term.fit();
        term.winptyCompatInit()
        term.webLinksInit()

        // 取得输入焦点
        term.focus();

        // 获取要连接的容器信息
        var podNs = document.getElementById("podNs").value
        var podName = document.getElementById("podName").value
        var containerName = document.getElementById("containerName").value

        // 连接websocket
        ws = new WebSocket("ws://localhost:7777/ssh?" + "podNs=" + podNs + "&podName=" + podName + "&containerName=" + containerName );
        ws.onopen = function(event) {
            console.log("onopen")
        }
        ws.onclose = function(event) {
            console.log("onclose")
        }
        ws.onmessage = function(event) {
            // 服务端ssh输出, 写到web shell展示
            term.write(event.data)
        }
        ws.onerror = function(event) {
            console.log("onerror")
        }

        // 当浏览器窗口变化时, 重新适配终端
        window.addEventListener("resize", function () {
            term.fit()

            // 把web终端的尺寸term.rows和term.cols发给服务端, 通知sshd调整输出宽度
            var msg = {type: "resize", rows: term.rows, cols: term.cols}
            ws.send(JSON.stringify(msg))

            // console.log(term.rows + "," + term.cols)
        })

        // 当向web终端敲入字符时候的回调
        term.on('data', function(input) {
            // 写给服务端, 由服务端发给container
            var msg = {type: "input", input: input}
            ws.send(JSON.stringify(msg))
        })
    }

    // 点击ssh建立websocket连接, 启动xterm终端
    document.getElementById("ssh").addEventListener("click", function() {
        document.getElementById('terminal').innerHTML = ""
        openTerminal()
    })
</script>
</body>
</html>